以Autofac為例
建立自訂的排程 JobActivator
GetChildScope() 建立新的子生命週期寫入私有欄位,並返回
/// <summary>
/// 排程Ioc容器解析器
/// </summary>
public class ContainerJobActivator : JobActivator
{
/// <summary>
/// 父容器
/// </summary>
public readonly IContainer Container;
/// <summary>
/// 容器物件子生命週期
/// </summary>
[ThreadStatic]
private static ILifetimeScope ChildScope;
/// <summary>
/// 建構式
/// </summary>
/// <param name="container">父容器</param>
public ContainerJobActivator(IContainer container)
{
this.Container = container;
}
/// <summary>
/// 解析物件為實體
/// </summary>
/// <param name="jobType">物件類型</param>
/// <returns>物件實體</returns>
public override object ActivateJob(Type jobType)
{
return ChildScope.Resolve(jobType);
}
/// <summary>
/// 取得容器物件子生命週期
/// </summary>
/// <returns>容器物件子生命週期</returns>
public ILifetimeScope GetChildScope()
{
ChildScope = Container.BeginLifetimeScope();
return ChildScope;
}
/// <summary>
/// 釋放容器物件子生命週期
/// </summary>
public void DisposeChildScope()
{
ChildScope.Dispose();
ChildScope = null;
}
}
建立自訂排程Filter
建構式傳入建立好的 JobActivator 實體
this.ContainerJobActivator.GetChildScope(),取出當前排程之LifetimeScope()
/// <summary>
/// 排程訊息推播註冊
/// </summary>
public class ObserverJobFilterAttribute : JobFilterAttribute, IServerFilter
{
/// <summary>
/// 排程Ioc容器解析物件
/// </summary>
private readonly ContainerJobActivator ContainerJobActivator;
/// <summary>
/// 建構式
/// </summary>
/// <param name="container">排程Ioc容器</param>
public ObserverJobFilterAttribute(ContainerJobActivator container)
{
this.ContainerJobActivator = container;
}
/// <summary>
/// 排程處理結束事件
/// </summary>
/// <param name="filterContext">filterContext</param>
public void OnPerformed(PerformedContext filterContext)
{
this.ContainerJobActivator.DisposeChildScope();
}
/// <summary>
/// 排程處理開始事件
/// </summary>
/// <param name="filterContext">filterContext</param>
public void OnPerforming(PerformingContext filterContext)
{
ILifetimeScope currentLifetimeScope = this.ContainerJobActivator.GetChildScope();
}
}
將hangfire納入autofac管理
選用自訂的容器解析器 containerJobActivator
加入filter
GlobalConfiguration.Configuration.UseAutofacActivator(container);
ContainerJobActivator containerJobActivator = new ContainerJobActivator(container);
JobActivator.Current = containerJobActivator;
GlobalJobFilters.Filters.Add(new ObserverJobFilterAttribute(containerJobActivator));